import React, { forwardRef, PureComponent } from 'react'
import { message } from 'antd'
import { connect } from '@umijs/max'
import { CreateDiffEditor } from '@/components'
import { getEnvDetail, saveEnv } from '../../../api'
import styles from './index.less'

class OperateRecord extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      spreadSta: false,
      taskNode: {},
      envDetail: '',
    }
  }

  // 进入工作流页面，第一次点击工作流程目标，此时页面还未加载
  componentDidMount() {
    this.setState(
      {
        taskNode: this.props?.taskNode,
      },
      () => {
        this.initData()
      },
    )
  }

  UNSAFE_componentWillUpdate(nextProps) {
    if (nextProps.taskNode != this.props.taskNode) {
      // eslint-disable-next-line react/no-will-update-set-state
      this.setState(
        {
          taskNode: nextProps.taskNode,
        },
        () => {
          this.initData()
        },
      )
    }
  }

  initData = () => {
    const { taskNode } = this.state
    const { nodeId } = taskNode || {}
    const params = {
      nodeId,
    }
    getEnvDetail(params).then((res) => {
      if (res.status === 200) {
        this.setState({
          envDetail: res.data || '',
        })
      }
    })
  }

  saveEnv = (env) => {
    const { taskNode } = this.state
    const { nodeId } = taskNode || {}
    saveEnv({ nodeId, env }).then((res) => {
      if (res.status === 200) {
        message.success(res.msg)
      } else {
        message.error(res.msg)
      }
    })
  }

  // eslint-disable-next-line react/no-unused-class-component-methods
  toggleOperateRecord = (spreadStaParams = undefined) => {
    if (!this.state.spreadSta) {
      this.initData()
    }
    this.setState((prevState) => ({
      spreadSta: spreadStaParams !== undefined ? spreadStaParams : !prevState.spreadSta,
    }))
  };

  render() {
    const {
      spreadSta, taskNode, envDetail,
    } = this.state
    const { nodeId } = taskNode || {}
    return (
      <div className={`${styles.node_detail} ${spreadSta ? styles.spread : ''}`}>
        <div className={styles.node_detail_column}>环境参数（保存ctrl+s）</div>
        <div className={styles.container}>
          <CreateDiffEditor
            theme={this.props?.themeValue==='light'?"vs":"vs-dark"}
            ref={this.editorEnvRef}
            language="sql"
            restData={envDetail}
            // realTimeSave={(val) => {
            //   this.saveEnv(val)
            // }}
            editorId={`real-time-task-parameter-editor${nodeId}`}
            onSave={(val) => {
              this.saveEnv(val)
            }}
          />
        </div>
      </div>
    )
  }
}

class WrappedComponentRef extends PureComponent {
  render() {
    const { forwardedRef, ...rest } = this.props
    return (
      <OperateRecord ref={forwardedRef} {...rest} />
    )
  }
}

const IComponent = connect(({ global,realTimeScriptDev }) => ({ themeValue:global.themeValue,...realTimeScriptDev }))(WrappedComponentRef)

export default forwardRef((props, ref) => <IComponent {...props} forwardedRef={ref} />)
